define(['common/js/service/boss-cart-service-0.1',
        'common/js/service/order-common-service-0.1',
        'common/js/service/crm-common-service-0.1'],
    function () {
        diretiveModule.directive('projectShopCart', ['$rootScope', 'CartSaleCommonService', 'CrmCommonRestService', 'MaiDialog', function ($rootScope, CartSaleCommonService, MaiDialog) {
            return {
                restrict: 'AE',
                scope: true,
                require: '?^plusUiSelect',
                controller: 'ProjectShopCartController',
                templateUrl: rootPath + '/common/js/html/plusCart.html',
                link: function (scope, iElement, iAttrs) {
                    try {
                        //是否允许选会员       true：可选 false：不可选  默认可选
                        scope.allowSelect = typeof(iAttrs.allowSelectCustomer) == "undefined" ? true : iAttrs.allowSelectCustomer;
                        //是否必须选择会员      true：必选选择一个会员  false：非必须   默认非必选
                        //scope.CustomerRequire = typeof(iAttrs.CustomerRequire) == "undefined"?false:params.CustomerRequire;
                        //判断来源
                        scope.sourceType = iAttrs.sourceType;
                        if (scope.sourceType == "2") {
                            //预订单转换
                            localStorage.removeItem("shopCart");
                            loadCustomer(scope.localparams.customerId);
                        } else {
                            scope.sourceType = "1";
                            scope.reloadEventDisCount({});
                        }
                        scope.$broadcast("reload-watchTicketFace", {"eventId": scope.localparams.eventId});
                    } catch (e) {
                        console.log(e);
                    }

                }
            };
        }]);

        controllerModule.controller("ProjectShopCartController", ['MaiDialog', '$scope', '$location', '$timeout', 'CartSaleCommonService', function (MaiDialog, $scope, $location, $timeout, CartSaleCommonService) {

            //刷新订单场次优惠
            $scope.reloadEventDisCount = function (params) {
                $timeout(function () {
                    $scope.$broadcast("reload-watchOrderEvent", {
                        "customerId": params.customerId,
                        "eventId": $scope.localparams.eventId
                    });//加载场次优惠
                }, 100);
            }

            //新增会员信息
            $scope.createCustomer = function () {
                $("#AddCustomerModal").modal("show");
            }
            //清空选项
            $scope.clearCustomer = function () {
                $scope.customerId = 0;
                $scope.$broadcast("reload-customerId", {"customerId": "load"});
                $scope.loadDiscountData();
                $scope.reloadEventDisCount({"customerId": 0});
                localStorage.removeItem("historyCustomer");
            }

            $scope.historyCustomer = function () {
                var historyCustomer = localStorage.getItem("historyCustomer");
                if (historyCustomer == null || typeof historyCustomer == "undefined") {
                    return;
                } else {
                    loadCustomer(historyCustomer);
                }
            }


            //精确查询手机号码
            window.loadCustomer = function (customerId) {
                $scope.customerDefault = customerId;
                $scope.$broadcast("reload-customerId", {"customerId": "disabled" + customerId});
                $scope.reloadEventDisCount({"customerId": customerId});
            }
            //选择用户后回调
            $scope.reload = function (params) {
                $scope.customerId = params.customerId;
                if ($scope.sourceType == "1") {
                    $scope.loadDiscountData();
                    localStorage.setItem("historyCustomer", params.customerId);
                    $scope.reloadEventDisCount({"customerId": $scope.customerId});
                } else {
                    $scope.customerShow = params.customerName;
                }
            }

            //显示购票记录
            $scope.showOrders = function () {
                if (typeof($scope.customerId) != "undefined" && $scope.customerId != 0) {
                    projectShopCartControllerShow($scope.customerId);
                } else {
                    MaiDialog.error("请先选择会员");
                }
            }
            //返回到选座页面
            $scope.backToSelectSeat = function () {
                if ($scope.sourceType == "1") {
                    localStorage.setItem("shopCartBack", "true")
                    $location.path("/view/sale/ppxsxz");
                } else {
                    $location.path("/view/order/advance_order_list");
                }
            }
            //选择票面下拉框输入
            $scope.selectAttr = function (params) {
                $scope.attr1 = false;
                $scope.attr2 = false;
                $scope.attr3 = false;
                var json = params.censusJson;
                if (json == null || typeof(json) == "undifined") {
                    return;
                }


                if (json.indexOf("orderFreeValue1") != -1) {
                    $scope.attr1 = true;
                }
                if (json.indexOf("orderFreeValue2") != -1) {
                    $scope.attr2 = true;
                }
                if (json.indexOf("orderFreeValue3") != -1) {
                    $scope.attr3 = true;
                }
            }
            //初始化票面元素
            $scope.initOrderAttr = function () {
                $scope.orderAttr1 = "";
                $scope.orderAttr2 = "";
                $scope.orderAttr3 = "";
            }

            //创建订单，弹出支付方式
            $scope.createOrder = function () {
                $("#pay-box").modal("show");
            }


            //local里面读取购物车数据
            $scope.loadLocalData = function () {
                $scope.localparams = localStorage.getItem("shopCart");
                if (typeof($scope.localparams) != "undifined") {
                    $scope.localparams = JSON.parse($scope.localparams);
                    $scope.customerId = $scope.localparams.customerId;
                    $scope.advanceOrderId = $scope.localparams.advanceOrderId;//预订单ID
                    $scope.goodsShare = {};
                    angular.forEach($scope.localparams.goodsList, function (good) {
                        $scope.goodsShare[good.goodsId] = good;
                    });
                }
            }
            //转换数据到local中
            $scope.changeLocalData = function () {
                localStorage.setItem("shopCart", JSON.stringify($scope.localparams));
            }


            //查询商品优惠折扣（购物车）
            $scope.loadDiscountData = function () {
                if ($scope.goodsConfirmVO.goodsCount == 0) {
                    return;
                }
                $scope.query = [];
                for (index in $scope.localparams.goodsList) {
                    $scope.query.push({
                        "goodsId": $scope.localparams.goodsList[index].goodsId,
                        "count": $scope.localparams.goodsList[index].count
                    });
                }

                var reqParams = {
                    'goodsList': $scope.query,
                    'selectSeatState': $scope.localparams.selectSeatState,
                    'customerId': $scope.customerId
                };
                CartSaleCommonService.queryGoodDiscount(reqParams).then(function (data) {
                	console.log(data);
                	if(data.msg == null || data.msg == 'undefined'){
                		MaiDialog.error(data.msg);
                		return;
                	}
                    $scope.goodsConfirmVO = data.data;
                    if ($scope.goodsConfirmVO == null || typeof $scope.goodsConfirmVO == "undefined") {
                        $scope.goodsConfirmVO = {};
                        MaiDialog.alert('购物车为空,请选择商品');
                    }
                    $("textarea").css("width", "500px");
                    $scope.initShopCart();
                });
            }

            //初始化信息
            $scope.initShopCart = function () {
                $scope.initGoodInfo();//初始化购物车信息
                $scope.analysis_g_t(); //计算商品折扣
                $scope.analysis_tp_t();//计算套票折扣
                $scope.dealOrderDiscount();//计算订单折扣
                $scope.countOrderMoney();//汇总信息
            }


            //统计所有商品价钱
            $scope.countOrderMoney = function () {
                //折扣总金额
                $scope.goodsConfirmVO.goodsCount = $scope.goodDiscountSelectVO.goodsCount + $scope.goodCouponSelectVO.goodsCount;
                $scope.goodsConfirmVO.derateMoney = decimalPoint(FloatAdd($scope.orderDiscountSelectVO.derateMoney, FloatAdd($scope.goodDiscountSelectVO.derateMoney, $scope.goodCouponSelectVO.derateMoney)));
                $scope.goodsConfirmVO.goodsPrice = decimalPoint(FloatAdd($scope.goodDiscountSelectVO.goodsPrice, $scope.goodCouponSelectVO.goodsPrice));
                $scope.goodsConfirmVO.buyPrice = decimalPoint(FloatSub($scope.goodsConfirmVO.goodsPrice, $scope.goodsConfirmVO.derateMoney));
            }

            //初始化变量
            $scope.goodsConfirmVO = {};
            $scope.goodDiscountSelectVO = {};//商品折扣商品
            $scope.goodCouponSelectVO = {};//套票商品
            $scope.orderDiscountModel = {};//订单折扣model
            $scope.orderDiscountSelectVO = {};//订单折扣
            $scope.orderParam = {};  //订单入参

            //初始换购物车
            $scope.initGoodInfo = function () {
                //自定义ng表单数据
                //$scope.orderDiscountModel = {};
                //订单商品总数
                $scope.goodsConfirmVO.buyPrice = 0.00;    //订单应付金额
                $scope.goodsConfirmVO.goodsPrice = 0.00;  //商品总金额
                $scope.goodsConfirmVO.derateMoney = 0.00; //优惠总金额
                $scope.goodsConfirmVO.goodsCount = 0;  //商品数量
                //商品折扣维度
                $scope.goodDiscountSelectVO = {};
                $scope.goodDiscountSelectVO.buyPrice = 0.00;    //商品应付金额
                $scope.goodDiscountSelectVO.goodsPrice = 0.00;  //商品总金额
                $scope.goodDiscountSelectVO.derateMoney = 0.00; //优惠总金额
                $scope.goodDiscountSelectVO.goodsCount = 0;   //商品总数量

                //套票商品维度
                $scope.goodCouponSelectVO = {}
                $scope.goodCouponSelectVO.buyPrice = 0.00;    //商品应付金额
                $scope.goodCouponSelectVO.goodsPrice = 0.00;  //商品总金额
                $scope.goodCouponSelectVO.derateMoney = 0.00; //优惠总金额
                $scope.goodCouponSelectVO.goodsCount = 0; //套票总数量
                //订单折扣维度
                $scope.orderDiscountSelectVO = {};
                $scope.orderDiscountSelectVO.derateMoney = 0.00;
                $scope.orderDiscountSelectVO.givePoint = 0;
                //初始化下单数据
                $scope.orderParam = {}; //初始化下单数组
                $scope.orderParam.orderGoodsDiscountParam = []//初始化明细


            }


            //处理商品优惠
            $scope.analysis_g_t = function () {
                console.log("====================遍历折扣商品开始=====================")
                if ($scope.goodsConfirmVO.discountGoodsVos == null || typeof($scope.goodsConfirmVO.discountGoodsVos) == "undefined" || $scope.goodsConfirmVO.discountGoodsVos.length == 0) {
                    console.log("非套票商品为空或者此商品已经取消授权");
                    return;
                }

                //计算优惠折扣金额
                angular.forEach($scope.goodsConfirmVO.discountGoodsVos, function (discountValue) {
                    discountValue.goodsMoney = 0.00;//优惠折扣商品总金额
                    discountValue.count = 0.00; //优惠折扣商品数量
                    discountValue.derateMoney = 0.00;//最后折扣优惠总金额
                    discountValue.realMoney = 0.00;//优惠折扣应收金额

                    //优惠折扣显示的才进行计算
                    if (discountValue.isShow == true) {
                        //折扣对象
                        var OrderGoodsDiscountParam = {};
                        $scope.orderParam.orderGoodsDiscountParam.push(OrderGoodsDiscountParam);
                        OrderGoodsDiscountParam['discountId'] = discountValue.discountId;
                        OrderGoodsDiscountParam['groupGoods'] = false;
                        OrderGoodsDiscountParam['orderGoodsParams'] = [];

                        //遍历商品获取商品数量goodsMoney和商品金额count 同时统计商品总数量
                        $scope.showFlag = true;
                        angular.forEach(discountValue.goodsBuyVOList, function (goodValue, $index) {
                            if (goodValue.isShow == true) {
                                //订单商品
                                console.log("ss-----------------------------------添加商品到订单明细项")
                                if ($scope.showFlag) {
                                    goodValue.showFlag = true;
                                    $scope.showFlag = false;
                                }
                                OrderGoodsDiscountParam['orderGoodsParams'].push($scope.convert(goodValue));
                                console.log("ee-----------------------------------添加商品到订单明细项")
                                //金额计算（商品总价）
                                discountValue.goodsMoney = window.FloatAdd(discountValue.goodsMoney, window.FloatMul(goodValue.price, goodValue.goodsCount));
                                discountValue.count += goodValue.goodsCount;//折扣数量
                                $scope.goodDiscountSelectVO.goodsCount += goodValue.goodsCount; //订单数量
                                //调整数字
                                goodValue.price = decimalPoint(goodValue.price);
                            }
                        }, discountValue);
                        discountValue.realMoney = discountValue.goodsMoney;
                        discountValue.derateMoney = 0.00;
                    }
                    discountValue.realMoney = decimalPoint(discountValue.realMoney);
                    discountValue.derateMoney = decimalPoint(discountValue.derateMoney);
                    discountValue.minShowMoney = decimalPoint(FloatSub(discountValue.minMoney, discountValue.goodsMoney));
                    $scope.goodDiscountSelectVO.buyPrice = window.FloatAdd($scope.goodDiscountSelectVO.buyPrice, discountValue.realMoney);
                    $scope.goodDiscountSelectVO.goodsPrice = window.FloatAdd($scope.goodDiscountSelectVO.goodsPrice, discountValue.goodsMoney);
                    $scope.goodDiscountSelectVO.derateMoney = window.FloatAdd($scope.goodDiscountSelectVO.derateMoney, discountValue.derateMoney);

                });
                console.log("====================遍历折扣商品结束=====================")
            }

            $scope.convert = function (goodValue) {
                var param = {};
                param["priceId"] = goodValue.priceId;
                param["goodCount"] = goodValue.goodsCount;
                param["goodPrice"] = goodValue.price;
                param["couponGroupId"] = goodValue.couponGroupId;
                //orderGoodsParam["couponGroupId"] = 0 //非套票;
                if ($scope.localparams.selectSeatState == 1) {
                    param["goodId"] = goodValue.goodsId;
                    param["superGoodId"] = goodValue.superGoodsId;
                } else if ($scope.localparams.selectSeatState == 2) {
                    param["goodId"] = 0;
                    param["superGoodId"] = goodValue.superGoodsId;
                }
                return param;
            }


            //计算套票的价钱
            $scope.analysis_tp_t = function () {
                console.log("=========================计算套票的价格开始===========================")
                if ($scope.goodsConfirmVO.coupnGoodList == null || typeof($scope.goodsConfirmVO.coupnGoodList) == "undefined" || $scope.goodsConfirmVO.coupnGoodList.length == 0) {
                    console.log("非套票商品为空或者此商品已经取消授权");
                    return;
                }

                angular.forEach($scope.goodsConfirmVO.coupnGoodList, function (couponGood) {
                    var OrderGoodsDiscountParam = {};
                    $scope.orderParam.orderGoodsDiscountParam.push(OrderGoodsDiscountParam);
                    OrderGoodsDiscountParam['discountId'] = 0;
                    OrderGoodsDiscountParam['groupGoods'] = true;
                    OrderGoodsDiscountParam['orderGroupGoodsParams'] = [];
                    couponGood.goodsPrice = 0;

                    angular.forEach(couponGood.couponGroupList, function (couponGroupVo) {
                        //考虑分组
                        var OrderGroupGoodsParam = {};
                        OrderGroupGoodsParam['orderGoodsParams'] = [];
                        OrderGroupGoodsParam['couponPriceId'] = couponGood.couponPriceId;
                        OrderGoodsDiscountParam.orderGroupGoodsParams.push(OrderGroupGoodsParam);
                        angular.forEach(couponGroupVo.goodsBuyVOList, function (goodValue) {
                            console.log("ss-----------------------------------添加套票商品到订单明细项");
                            OrderGroupGoodsParam['orderGoodsParams'].push($scope.convert(goodValue));
                            goodValue.price = decimalPoint(goodValue.price);
                            couponGood.goodsPrice = FloatAdd(couponGood.goodsPrice, FloatMul(goodValue.price, goodValue.goodsCount));
                            console.log("ee-----------------------------------添加套票商品到订单明细项")
                            $scope.goodCouponSelectVO.goodsCount += goodValue.goodsCount; //订单数量
                        }, OrderGroupGoodsParam);
                    }, couponGood);

                    couponGood.showMoney = decimalPoint(FloatMul(couponGood.couponPrice, couponGood.couponCount));
                    couponGood.derateShowMoney = decimalPoint(FloatSub(couponGood.goodsPrice, couponGood.showMoney));

                    $scope.goodCouponSelectVO.goodsPrice = FloatAdd($scope.goodCouponSelectVO.goodsPrice, couponGood.goodsPrice);//套票商品金额
                    $scope.goodCouponSelectVO.buyPrice = FloatAdd($scope.goodCouponSelectVO.buyPrice, FloatMul(couponGood.couponPrice, couponGood.couponCount));//套票应收金额
                });
                //套票优惠显示
                $scope.goodCouponSelectVO.derateMoney = FloatSub($scope.goodCouponSelectVO.goodsPrice, $scope.goodCouponSelectVO.buyPrice);
                console.log("=========================计算套票的价格结束===========================")
            }


            $scope.changeEventDiscount = function (n_v) {
                if (typeof(n_v) == "undefined") {
                    return;
                }
                $scope.orderDiscountModel = n_v;
                if (n_v.discountRule == 1201 && n_v.discountRuleDefineValue != 0) {
                    //满减（自定义）
                    $scope.orderDiscountMoney = '';
                }
                $scope.dealOrderDiscount();
                $scope.countOrderMoney();
            }

            //监听下拉框
            /*		$scope.$watch("orderDiscountModel",function(n_v,o_v){
             if(typeof(n_v) == "undefined" ){
             return;
             }
             if(typeof n_v.discountRule == "undefined"){
             return;
             }
             if(n_v.discountRule==1201&&n_v.discountRuleDefineValue!=0){
             //满减（自定义）
             $scope.orderDiscountMoney = '';
             }
             $scope.dealOrderDiscount();
             $scope.countOrderMoney();
             });*/

            //处理订单优惠--通过选择下拉框
            $scope.dealOrderDiscount = function () {
                console.log("====================计算订单折扣开始=====================")
                $scope.userDefineMoney = decimalPoint(0);
                $scope.orderDiscountSelectVO = (typeof $scope.orderDiscountSelectVO == "undefined") ? {} : $scope.orderDiscountSelectVO;
                $scope.orderDiscountSelectVO.derateMoney = decimalPoint(0);
                if ($scope.orderDiscountModel == null || $scope.orderDiscountModel.eventDiscountId == 0) {
                    return;
                }
                if ($scope.orderDiscountModel.discountRule == 1201 && $scope.orderDiscountModel.discountRuleDefineValue != '') {
                    //自定义优惠金额
                    return;
                }
                $scope.orderDiscountSelectVO.derateMoney = 0.00;
                //满减（无上限）
                var buyPrice = FloatAdd($scope.goodDiscountSelectVO.buyPrice, $scope.goodCouponSelectVO.buyPrice);
                if ($scope.orderDiscountModel.discountRule == 1201
                    && buyPrice >= $scope.orderDiscountModel.goodMoneyFull
                    && $scope.goodsConfirmVO.goodsCount >= $scope.orderDiscountModel.goodCountsFull
                ) {
                    $scope.orderDiscountSelectVO.derateMoney = $scope.orderDiscountModel.discountRuleValue;
                } else if ($scope.orderDiscountModel.discountRule == 1201
                    && (buyPrice < $scope.orderDiscountModel.goodMoneyFull || $scope.goodsConfirmVO.goodsCount < $scope.orderDiscountModel.goodCountsFull)) {
                    MaiDialog.error("此订单不满足所选优惠的使用条件，请重新选择");
                    return;
                }

                //满折
                if ($scope.orderDiscountModel.discountRule == 1202
                    && buyPrice >= $scope.orderDiscountModel.goodMoneyFull
                    && $scope.goodsConfirmVO.goodsCount >= $scope.orderDiscountModel.goodCountsFull
                ) {
                	//折扣为小数的情况需要注意
                    $scope.orderDiscountSelectVO.derateMoney = parseFloat(FloatDiv(FloatMul(buyPrice, 10 - $scope.orderDiscountModel.discountRuleValue), 10)).toFixed(2);
                    if ($scope.orderDiscountModel.upperLimmit) {
                        //有折扣上限
                        if ($scope.orderDiscountModel.discountRuleDefineValue < $scope.orderDiscountSelectVO.derateMoney) {
                            $scope.orderDiscountSelectVO.derateMoney = $scope.orderDiscountModel.discountRuleDefineValue;
                        }
                    } else {
                        if ($scope.orderDiscountModel.discountRuleDefineValue != 0 && $scope.orderDiscountModel.discountRuleDefineValue < $scope.orderDiscountSelectVO.derateMoney) {
                            $scope.orderDiscountSelectVO.derateMoney = $scope.orderDiscountModel.discountRuleDefineValue;
                        }
                    }
                } else if ($scope.orderDiscountModel.discountRule == 1202
                    && (buyPrice < $scope.orderDiscountModel.goodMoneyFull || $scope.goodsConfirmVO.goodsCount < $scope.orderDiscountModel.goodCountsFull)) {
                    MaiDialog.error("此订单不满足所选优惠的使用条件，请重新选择");
                    return;
                }

                //赠送积分
                if ($scope.orderDiscountModel.discountRule == 1203
                    && buyPrice >= $scope.orderDiscountModel.goodMoneyFull
                    && $scope.goodsConfirmVO.goodsCount >= $scope.orderDiscountModel.goodCountsFull) {
                    $scope.orderDiscountSelectVO.givePoint = $scope.orderDiscountModel.discountRuleValue;
                } else if ($scope.orderDiscountModel.discountRule == 1203
                    && (buyPrice < $scope.orderDiscountModel.goodMoneyFull || $scope.goodsConfirmVO.goodsCount < $scope.orderDiscountModel.goodCountsFull)) {
                    MaiDialog.error("此订单不满足所选优惠的使用条件，请重新选择");
                    return;
                }

                $scope.orderDiscountMoney = $scope.orderDiscountSelectVO.derateMoney;
                console.log("====================计算订单折扣结束=====================")
            }

            //监听自定义金额变化
            $scope.$watch("orderDiscountMoney", function (n_v, o_v) {
                var rexq = new RegExp(/^(([1-9]\d*)|0)(\.\d{1,2})?$/);
                if (typeof(n_v) != "undefined" && n_v != "") {

                    if ((n_v + "").charAt(n_v.length - 1) == ".") {
                        return;
                    }

                    if (!rexq.test(n_v) || n_v > 1000000) {
                        MaiDialog.error('请输入正确减免金额<br>【1.不大于1000000的有效金额】<br>【2.最多保留两位有效数字】', function () {
                            $scope.agreeFlag = false;
                        });
                        $scope.orderDiscountMoney = o_v;
                        $scope.orderDiscountSelectVO.derateMoney = o_v;
                    } else {
                        $scope.orderDiscountMoney = n_v;
                        $scope.orderDiscountSelectVO.derateMoney = n_v;
                    }
                    if ($scope.orderDiscountModel.discountRuleDefineValue != 0 && n_v > $scope.orderDiscountModel.discountRuleDefineValue) {
                        $scope.orderDiscountMoney = $scope.orderDiscountModel.discountRuleDefineValue;
                        $scope.orderDiscountSelectVO.derateMoney = $scope.orderDiscountModel.discountRuleDefineValue;
                    }
                    $scope.countOrderMoney();//汇总信息

                    if ($scope.goodsConfirmVO.buyPrice < 0) {
                        MaiDialog.error('订单总金额不能小于0');
                        $scope.orderDiscountMoney = FloatAdd($scope.orderDiscountMoney, $scope.goodsConfirmVO.buyPrice);
                        $scope.orderDiscountSelectVO.derateMoney = $scope.orderDiscountMoney;
                        $scope.countOrderMoney();//汇总信息
                    }
                } else {
                    $scope.orderDiscountMoney = n_v;
                    if ($scope.orderDiscountSelectVO != null) {
                        $scope.orderDiscountSelectVO.derateMoney = 0;
                        $scope.countOrderMoney();//汇总信息
                    }
                }
            });

            //删除折扣商品信息
            $scope.del_c_g = function (goodsId, goodsCount, discountId) {
                angular.forEach($scope.goodsConfirmVO.discountGoodsVos, function (discountValue) {
                    var count = discountValue.count;
                    if (discountValue.discountId == discountId) {
                        //变更状态
                        angular.forEach(discountValue.goodsBuyVOList, function (goodValue) {
                            if (goodValue.goodsId == goodsId) {
                                goodValue.isShow = false;
                                goodValue.isDelete = true;
                                count = window.FloatSub(count, goodValue.goodsCount);
                            }
                        });
                        //修改折扣状态
                        if (count <= 0) {
                            discountValue.isShow = false;
                        }
                    }
                });

                if ($scope.goodsShare[goodsId].count == goodsCount) {
                    delete $scope.goodsShare[goodsId];
                } else {
                    $scope.goodsShare[goodsId].count = $scope.goodsShare[goodsId].count - goodsCount;
                }
                $scope.localparams.goodsList = $scope.display($scope.goodsShare);
                $scope.changeLocalData();//修改记录
                $scope.initShopCart();
            }


            //删除套票
            $scope.del_t_g = function (goodsId, goodsCount, couponGroupId) {
                var fixed = true;
                if (couponGroupId == 0) {
                    fixed = false;
                }

                if (fixed) {
                    //遍历固定套票处理
                    angular.forEach($scope.goodsConfirmVO.coupnGoodList, function (couponGood) {
                        angular.forEach(couponGood.couponGroupList, function (couponGroup) {
                            if (couponGroup.couponGroupId == couponGroupId) {
                                angular.forEach(couponGroup.goodsBuyVOList, function (goods) {
                                    delete $scope.goodsShare[goods.goodsId];
                                });
                            }
                        });
                    });
                } else {
                    if ($scope.goodsShare[goodsId].count == goodsCount) {
                        delete $scope.goodsShare[goodsId];
                    } else {
                        $scope.goodsShare[goodsId].count = $scope.goodsShare[goodsId].count - goodsCount;
                    }
                }
                $scope.localparams.goodsList = $scope.display($scope.goodsShare);
                $scope.changeLocalData();//修改记录
                $scope.loadDiscountData()
            }


            $scope.display = function (obj) {
                var goodsList = [];
                for (var name in obj) {
                    goodsList.push({"goodsId": name, "count": obj[name].count, "seatId": obj[name].seatId})
                }
                return goodsList;
            }

            $scope.init = function () {
                $(window).scroll(function () {
                    var scrollValue = $(window).scrollTop();
                    scrollValue > 100 ? $('#bk-t').fadeIn() : $('#bk-t').fadeOut();
                });

                $('#bk-t').click(function () {
                    $('html,body').animate({
                        scrollTop: 0
                    }, 500);
                });
                $('#tk-seting').on('hide.bs.collapse', function () {
                    $('.btn-sh').addClass('btn-sh-2').removeClass('btn-sh-1');
                }).on('show.bs.collapse', function () {
                    $('.btn-sh').addClass('btn-sh-1').removeClass('btn-sh-2');
                });
            }


            $scope.place = function () {
                $scope.orderParam['advanceOrderId'] = $scope.advanceOrderId;
                $scope.orderParam['customerId'] = $scope.customerId;
                $scope.orderParam['orderBillTypeId'] = $scope.ticketTypeModel.orderBillTypeId;
                $scope.orderParam['ticketFaceId'] = $scope.ticketFaceModel.ticketFaceId;
                if ($scope.orderAttr1 != null && $scope.orderAttr1.length > 20) {
                    MaiDialog.error("订单自由量1最多20字");
                    return;
                }
                if ($scope.orderAttr2 != null && $scope.orderAttr2.length > 20) {
                    MaiDialog.error("订单自由量2最多20字");
                    return;
                }
                if ($scope.orderAttr3 != null && $scope.orderAttr3.length > 20) {
                    MaiDialog.error("订单自由量3最多20字");
                    return;
                }
                if ($scope.remark != null && $scope.remark.length > 50) {
                    MaiDialog.error("订单备注最多50字");
                    return;
                }

                if ($scope.orderDiscountModel.eventDiscountId == 1) {
                    if ($scope.orderDiscountMoney == '') {
                        MaiDialog.error("自定义减免金额不能为空");
                        return;
                    }
                }

                $scope.orderParam['orderAttr1'] = $scope.orderAttr1;
                $scope.orderParam['orderAttr2'] = $scope.orderAttr2;
                $scope.orderParam['orderAttr3'] = $scope.orderAttr3;
                $scope.orderParam['orderDiscountId'] = $scope.orderDiscountModel.eventDiscountId;
                $scope.orderParam['orderDiscountMoney'] = $scope.orderDiscountMoney;
                $scope.orderParam['remark'] = $scope.remark;
                $scope.orderParam['orderMoney'] = $scope.goodsConfirmVO.goodsPrice;
                $scope.orderParam['realMoney'] = $scope.goodsConfirmVO.goodsPrice;
                $scope.orderParam['receivableMoney'] = $scope.goodsConfirmVO.buyPrice;
                //票类型默认为1 纸质票
                $scope.orderParam['ticketType'] = 1;
                var buyPrice = FloatAdd($scope.goodDiscountSelectVO.buyPrice, $scope.goodCouponSelectVO.buyPrice);
                console.log($scope.orderParam);
                if (buyPrice < $scope.orderDiscountModel.goodMoneyFull
                    || $scope.goodsConfirmVO.goodsCount < $scope.orderDiscountModel.goodCountsFull) {
                    MaiDialog.error("此订单不满足所选优惠的使用条件，请重新选择");
                    return;
                } else {
                    CartSaleCommonService.createOrder($scope.orderParam).then(function (data) {
                        //下单参数
                        data.sCustomerId = $scope.customerId;
                        data.receivableMoney = $scope.goodsConfirmVO.buyPrice;
                        if ($scope.orderParam['orderBillTypeId'] == 1) {
                            showPayType(data);
                        } else {
                            //非正常票直接出票
                            showModal(data);
                        }
                    })
                }

            }

            $scope.init();
            $scope.loadLocalData();
            $scope.loadDiscountData();


        }]);


        //新增会员
        controllerModule.controller("SaleAddCustomerController", function ($scope, $rootScope, $routeParams, $location, CartSaleCommonService, MaiDialog) {
            $scope.CustomerValidation = {
                customerName: {
                    required: "名称为必填字段",
                    pattern: "请重新输入1-20位有效字符的姓名（汉字、字母、数字）"
                },
                customerTel: {
                    pattern: "请输入11位有效电话"
                },
                customerEmail: {
                    pattern: "请输入有效的邮箱格式"
                },
                customerAddress: {
                    maxlength: "地址在30个字符内"
                },
                remark: {
                    maxlength: "备注在50个字符内"
                }

            };

            $scope.birthDayPickerOpt = {
                format: 'yyyy-mm-dd',
                minView: 'month',
                startView: 'month',
                startDate: "1890-01-01"
            };


            $scope.blur = function () {
                var id = $scope.searchConditions['customerCard'];
                if (typeof (id) == 'string' && id.length == 18) {
                    var year = id.substr(6, 4);
                    var month = id.substr(10, 2);
                    var day = id.substr(12, 2);
                    if ($scope.validateBirthday(year, month, day)) {
                        $scope.searchConditions['customerBirthday'] = year + '-' + month + '-' + day;
                    }

                }
            };
            $scope.validateBirthday = function (year, month, day) {

                if (Number(year) < 1800 || Number(month) > 12 || Number(day) > 31) {
                    $scope.$broadcast("setFormMsg-CustomerForm", "请输入有效的身份证！出生日期有误!");
                    return false;
                }
                $scope.$broadcast("setFormMsg-CustomerForm", "");
                return true;
            }

            $scope.addCustomerDo = function (params) {

                if (typeof(params.customerBirthday) == 'undefined' || params.customerBirthday == "") {
                    params.customerBirthday = formatDate(now);
                }
                if (Date.parse(params.customerBirthday) > new Date()) {
                    $scope.$broadcast("setFormMsg-CustomerForm", "生日不能晚于今天");
                    return false;
                }
                if (typeof(params.customerCard) != "undefined" && params.customerCard != "") {
                    var re = /^\d{17}(\d|X|x)$/;
                    if ((!re.exec(params.customerCard))) {
                        $scope.$broadcast("setFormMsg-CustomerForm", "请输入有效的身份证");
                        return false;
                    }
                    var year = params.customerCard.substr(6, 4);
                    var month = params.customerCard.substr(10, 2);
                    var day = params.customerCard.substr(12, 2);

                    if (!$scope.validateBirthday(year, month, day)) {
                        return false;
                    }
                }
                if (typeof(params.customerEmail) != "undefined" && params.customerEmail.length > 50) {
                    $scope.$broadcast("setFormMsg-CustomerForm", "邮箱长度太长");
                    return false;
                }
                params.customerTel = typeof(params.customerTel) == "undefined" ? "" : params.customerTel;
                params.customerEmail = typeof(params.customerEmail) == "undefined" ? "" : params.customerEmail;

                if (params.customerTel == "" && params.customerEmail == "") {
                    $scope.$broadcast("setFormMsg-CustomerForm", "手机、邮箱至少填写一项");
                    return false;
                }
                if (typeof(params.customerSex) == "object") {
                    params.customerSex = params.customerSex.code;
                }
                if (typeof(params.customerType) == "object") {
                    params.customerType = params.customerType.id;
                }
                if (typeof(params.customerLevel) == "object") {
                    params.customerLevel = params.customerLevel.id;
                }

                CartSaleCommonService.saveCustomer(params).then(function (data) {
                    console.log(data);
                    $scope.$broadcast("clearForm-CustomerForm");
                    $scope.hide();
                    loadCustomer(data);
                })
            }

            $scope.cancelCustomerDo = function () {
                $scope.hide();
            }

            $scope.hide = function () {
                $("#AddCustomerModal").modal("hide");
                //setTimeout(function(){document.body.className = "skin-blue fixed tooltip-f modal-open";},500);
            }


        });


        controllerModule.controller("PayTypeController", function ($scope, $rootScope, $location,
                                                                   OrderCommonRestService, CartSaleCommonService, OutletCardService, MaiDialog) {

            //use define param
            $scope.init = function () {
                $scope.userForm = {};
                $scope.userForm.payFlag = false; //是否可以支付
                $scope.userForm.debt = false;//是否欠款打印
                //余额
                $scope.banlanceForm = {};
                $scope.banlanceForm.showPayPwd = false;//显示密码
                $scope.banlanceForm.banlanceFlag = false;//是否可以输入余额

                $scope.banlanceForm.useBanlance = 0;//用户余额
                $scope.banlanceForm.banlanceMsg = '';//余额错误提示
                $scope.banlanceForm.banlanceMoney = 0; //用户输入余额
                $scope.banlanceForm.banlancePwd = '' //余额支付密码

                //积分
                $scope.pointForm = {};
                $scope.pointForm.pointFlag = false;//是否可以输入余额
                $scope.pointForm.deductibleMoney = 0;//积分抵扣金额
                $scope.pointForm.usePoint = 0;//输入积分
                $scope.pointForm.point = 0;//剩余总积分
                $scope.pointForm.availablePoint = 0;//可用积分
                $scope.pointForm.pointMsg = '';//积分错误提示

                //礼品卡
                $scope.cardForm = {};
                $scope.cardForm.showCardPwd = false;//是否显示礼品卡支付
                $scope.cardForm.giftCardNo = '';//礼品卡id
                $scope.cardForm.leftCardMoney = 0;//礼品卡可用余额
                $scope.cardForm.useCardMoney = 0;//礼品卡支付金额
                $scope.cardForm.cardPwd = '';//礼品卡支付密码
                $scope.cardForm.cardMsg = '';//礼品卡错误提示

                //普通支付方式
                $scope.payTypeVOList = {};
                $scope.payMoneyError = '';
            }
            $scope.init();
            //校验输入正则
            var rexq = new RegExp(/^(([1-9]\d*)|0)(\.\d{1,2})?$/);

            $scope.close = function () {
                $("#pay-box").modal("hide");
                if ($scope.sourceType == "1") {
                    $location.path("/view/sale/ppxsxz");
                } else {
                    $location.path("/view/order/advance_order_list");
                }
                //$location.path("/view/sale/ppxsxz");
            }

            window.showPayType = function (params) {
                console.log("***********showPayType***********");
                console.log(params);
                $scope.init();
                if (params == null || typeof(params) == "undefined") {
                    params = {};
                }
                $scope.order = params;
                $scope.PointRuleVO = {"point": 0};


                if ($scope.order.receivableMoney == 0) {
                    $scope.userForm.payFlag = true;
                }

                $scope.order.showMoney = decimalPoint($scope.order.receivableMoney);
                $("#pay-box").modal("show")
                //获取普通方式支付
                CartSaleCommonService.getOrderPayType().then(function (data) {
                    for (var o in data) {
                        if (data[o].payTypeId == 9) {
                            data.splice(o, 1);
                        }
                    }
                    $scope.payTypeVOList = data
                    console.log(data);
                });
                //获取余额和积分支付;
                $scope.customer = {};
                if ($scope.order.sCustomerId != null && $scope.order.sCustomerId != "0" && typeof($scope.order.sCustomerId) != "undefined") {
                    CartSaleCommonService.findCustomerPayInfo({"customerId": $scope.order.sCustomerId}).then(function (data) {
                        console.log(data);
                        $scope.customer = data;
                        if ($scope.customer.accountState == -1) {
                            $scope.banlanceForm.banlanceFlag = true;
                            $scope.banlanceForm.banlanceMsg = "【未开通余额支付】"
                            //$scope.pointForm.pointFlag = true;//是否可以输入余额
                            //$scope.pointForm.pointMsg = '【未开通会员账户】';//积分错误提示
                            $scope.pointForm.point = $scope.customer.point;
                            if ($scope.pointForm.point == 0) {
                                $scope.pointForm.pointMsg = '【账户可用积分为0，暂不支持积分支付】'
                            }
                        } else if ($scope.customer.accountState == 1) {
                            $scope.banlanceForm.banlanceFlag = true;
                            $scope.banlanceForm.banlanceMsg = "【账户已经被禁用】"
                            //$scope.pointForm.pointFlag = true;//是否可以输入余额
                            //$scope.pointForm.pointMsg = '【账户已经被禁用】';//积分错误提示
                            $scope.pointForm.point = $scope.customer.point;
                            if ($scope.pointForm.point == 0) {
                                $scope.pointForm.pointMsg = '【账户可用积分为0，暂不支持积分支付】'
                            }
                        } else if ($scope.customer.accountState == 2) {
                            $scope.banlanceForm.useBanlance = $scope.customer.money
                            if ($scope.banlanceForm.useBanlance == 0) {
                                $scope.banlanceForm.banlanceMsg = "【账户余额为0，暂不支持余额支付】"
                            }
                            $scope.pointForm.point = $scope.customer.point;
                            if ($scope.pointForm.point == 0) {
                                $scope.pointForm.pointMsg = '【账户可用积分为0，暂不支持积分支付】'
                            }
                        }

                        if(!$scope.pointForm.pointFlag){
                            //调用查询积分规则
                            CartSaleCommonService.findCustomerPointRule().then(function (data) {
                                console.log(data);
                                if (data != null && typeof(data.id) != "undefined" && data.id != 0) {
                                    $scope.PointRuleVO = data;
                                    if (data.orderPercent != 0) {
                                        //可用金额
                                        var needUsemoney = FloatDiv(FloatMul($scope.order.receivableMoney, data.orderPercent), 100);
                                        if (needUsemoney >= data.money) {
                                            var count = parseInt(FloatDiv(needUsemoney, data.money));
                                            //可抵扣总金额
                                            $scope.PointRuleVO.allMoney = FloatMul(count, data.money);
                                            var tjpoint = FloatMul(count, data.point);
                                            //可用支付积分大于总积分
                                            if (tjpoint > $scope.pointForm.point && $scope.pointForm.point >0) {
                                                $scope.pointForm.availablePoint = $scope.pointForm.point - ($scope.pointForm.point%data.point);
                                                //$scope.pointForm.availablePoint = 0;
                                            }else if($scope.pointForm.point <=0){
                                            	$scope.pointForm.availablePoint = 0;
                                            }else {
                                                $scope.pointForm.availablePoint = parseInt(tjpoint);
                                            }
                                        }
                                    }
                                }
                            });
                        }

                    });

                } else {
                    $scope.banlanceForm.banlanceFlag = true;
                    $scope.banlanceForm.banlanceMsg = "【非会员下单，无法使用余额支付】"
                    $scope.pointForm.pointFlag = true;//是否可以输入余额
                    $scope.pointForm.pointMsg = '【非会员下单，无法使用积分支付】';//积分错误提示
                }


                $scope.count();

            }

            $scope.selectCommonPayType = function (params) {
                console.log(params);
                var money = params.payType.exp1;
                if (money == null || money == "") {
                    money = 0;
                }

                if (typeof(money) != "undefined") {
                    if (!rexq.test(money)) {
                        $scope.payTypeVOList[params.$index].exp1 = $scope.payTypeVOList[params.$index].exp2;
                        MaiDialog.error('请输入正确金额<br>', function () {
                            setTimeout(function () {
                                document.body.className = "skin-blue fixed tooltip-f modal-open";
                            }, 1000);
                        });
                        return;
                    } else {
                        if (money > 100000) {
                            money = 100000;
                            MaiDialog.error('输入金额最多100000元<br>', function () {
                                setTimeout(function () {
                                    document.body.className = "skin-blue fixed tooltip-f modal-open";
                                }, 1000);
                            });
                        }
                        $scope.payTypeVOList[params.$index].exp1 = money;
                        $scope.payTypeVOList[params.$index].exp2 = money;
                    }
                }
                $scope.count();
            }


            //选择余额
            $scope.selectBanlance = function () {
                if ($scope.banlanceForm.banlanceFlag)return;

                $scope.banlanceForm.banlanceMsg = '';//提示设置空
                if ($scope.banlanceForm.banlanceMoney == null || $scope.banlanceForm.banlanceMoney == "" || $scope.banlanceForm.banlanceMoney == 0) {
                    $scope.banlanceForm.showPayPwd = false;
                    $scope.banlanceForm.banlancePwd = '';
                    $scope.banlanceForm.banlanceMoney = 0;
                    $scope.count();
                    return;
                }

                if (typeof($scope.banlanceForm.banlanceMoney) != "undefined") {
                    if (!rexq.test($scope.banlanceForm.banlanceMoney)) {
                        $scope.banlanceForm.banlanceMsg = '【最多保留两位有效数字】';
                        $scope.banlanceForm.banlanceMoney = 0;
                        $scope.banlanceForm.banlancePwd = '';
                        $scope.banlanceForm.showPayPwd = false;
                    } else {
                        $scope.banlanceForm.showPayPwd = true;
                    }
                    if ($scope.banlanceForm.banlanceMoney > $scope.banlanceForm.useBanlance) {
                        $scope.banlanceForm.banlanceMsg = '【余额不足】';
                        $scope.banlanceForm.banlanceMoney = $scope.banlanceForm.useBanlance;
                    }

                    if ($scope.banlanceForm.banlanceMoney > 100000) {
                        $scope.banlanceForm.banlanceMsg = '【余额金额不能超过100000元】';
                        $scope.banlanceForm.banlanceMoney = 100000;
                    }
                    $scope.count();
                }
            }

            //积分输入
            $scope.selectPoint = function () {
                if ($scope.pointForm.pointFlag || $scope.pointForm.availablePoint == 0)return;
                $scope.pointForm.pointMsg = '';
                if ($scope.pointForm.usePoint == null || $scope.pointForm.usePoint == "") {
                    $scope.pointForm.usePoint = 0;
                    $scope.pointForm.deductibleMoney = 0;
                    $scope.count();
                    return;
                }

                if (typeof($scope.pointForm.usePoint) != "undefined") {
                    if (!new RegExp(/^[0-9]*[1-9][0-9]*$/).test($scope.pointForm.usePoint)) {
                        $scope.pointForm.pointMsg = '【请输入正整数】';
                        $scope.pointForm.usePoint = 0;
                        $scope.pointForm.deductibleMoney = 0;
                    }

                    var count = parseInt(FloatDiv($scope.pointForm.usePoint, $scope.PointRuleVO.point));
                    $scope.pointForm.usePoint = parseInt(FloatMul(count, $scope.PointRuleVO.point));
                    if ($scope.pointForm.usePoint > $scope.pointForm.availablePoint) {
                        $scope.pointForm.pointMsg = '【积分不能超过可用积分】';
                        $scope.pointForm.usePoint = $scope.pointForm.availablePoint;
                        $scope.pointForm.deductibleMoney = $scope.PointRuleVO.allMoney;
                    } else {
                        //折扣金额
                        $scope.pointForm.deductibleMoney = FloatMul(count, $scope.PointRuleVO.money)
                    }
                    $scope.count();
                }
            }
            //读取礼品卡
            $scope.reloadCard = function () {
                var params = {
                    "giftCardNo": $scope.cardForm.giftCardNo
                };
                $scope.cardForm.cardMsg = "";
                OutletCardService.findOrderCard(params).then(function (data) {
                    if (data.totalResults == 1) {
                        $scope.cardForm.leftCardMoney = data.data[0].giftCardBalance;
                        $scope.cardForm.showCardPwd = true;
                    } else {
                        $scope.cardForm.cardMsg = "未查到该礼品卡";
                        $scope.cardForm.leftCardMoney = 0;
                        $scope.cardFrom.showCardPwd = false;
                    }
                });
            }
            //使用礼品卡支付
            $scope.selectCard = function () {
                $scope.cardForm.cardMsg = "";
                if ($scope.cardForm.useCardMoney > $scope.cardForm.leftCardMoney) {
                    $scope.cardForm.cardMsg = "余额使用超出上限";
                    $scope.cardForm.useCardMoney = 0;
                }
                $scope.count();
            }
            //统计费用+是否显示可以支付
            $scope.count = function () {

                $scope.order = typeof( $scope.order) == "undefined" ? {} : $scope.order;
                $scope.OrdersPayParam = {};
                $scope.OrdersPayParam.orderPayTypeParams = [];
                $scope.OrdersPayParam.orderId = $scope.order.sOrderId;
                $scope.OrdersPayParam.debtMoney = 0;
                $scope.OrdersPayParam.realMoney = 0;
                $scope.order.showMoney = 0;
                $scope.payMoneyError = '';
                
                $scope.OrdersPayParam.orderId = $scope.order.sOrderId;
                //普通支付方式
                angular.forEach($scope.payTypeVOList, function (payTypeVO) {
                    if (payTypeVO.exp1 > 0) {
                        var OrderPayTypeParam = {};
                        OrderPayTypeParam.orderPayTypeId = payTypeVO.payTypeId;
                        OrderPayTypeParam.money = payTypeVO.exp1;
                        $scope.OrdersPayParam.orderPayTypeParams.push(OrderPayTypeParam);
                        $scope.OrdersPayParam.realMoney = FloatAdd($scope.OrdersPayParam.realMoney, payTypeVO.exp1);
                    }
                }, $scope.OrdersPayParam.orderPayTypeParams);
                //余额支付
                if ($scope.banlanceForm.banlanceMoney > 0) {
                    var balanceOrderPayTypeParam = {
                        "orderPayTypeId": 3,
                        "money": $scope.banlanceForm.banlanceMoney,
                        "payPassword": $scope.banlanceForm.banlancePwd
                    }
                    $scope.OrdersPayParam.realMoney = FloatAdd($scope.OrdersPayParam.realMoney, $scope.banlanceForm.banlanceMoney);
                    $scope.OrdersPayParam.orderPayTypeParams.push(balanceOrderPayTypeParam);
                }
                //积分支付
                if ($scope.pointForm.usePoint > 0) {
                    var pointOrderPayTypeParam = {
                        "orderPayTypeId": 4,
                        "money": $scope.pointForm.deductibleMoney,
                        "pointCount": parseInt($scope.pointForm.usePoint)
                    }
                    $scope.OrdersPayParam.realMoney = FloatAdd($scope.OrdersPayParam.realMoney, $scope.pointForm.deductibleMoney);
                    $scope.OrdersPayParam.orderPayTypeParams.push(pointOrderPayTypeParam);
                }
                //礼品支付
                if ($scope.cardForm.useCardMoney > 0) {
                    var pointOrderPayTypeParam = {
                        "orderPayTypeId": 9,
                        "money": $scope.cardForm.useCardMoney,
                        "payPassword": $scope.cardForm.cardPwd
                    }
                    $scope.OrdersPayParam.realMoney = FloatAdd($scope.OrdersPayParam.realMoney, $scope.cardForm.useCardMoney);
                    $scope.OrdersPayParam.orderPayTypeParams.push(pointOrderPayTypeParam);
                }
                $scope.OrdersPayParam.debtMoney = FloatSub($scope.order.receivableMoney, $scope.OrdersPayParam.realMoney);
                $scope.order.showMoney = $scope.OrdersPayParam.debtMoney;
                if ($scope.userForm.debt && $scope.order.showMoney > 0) {
                    $scope.userForm.payFlag = true;
                } else {
                    $scope.userForm.payFlag = false;
                }
                /*	if(!$scope.userForm.debt&&$scope.order.showMoney == 0){
                 $scope.userForm.payFlag = true;
                 }
                 */
                if ($scope.order.showMoney < 0) {
                	$scope.payMoneyError = '支付金额超出订单'+Math.abs($scope.order.showMoney)+'元';
                    $scope.userForm.debt = false;
                    $scope.userForm.payFlag = false;
                }
                if ($scope.order.showMoney == 0) {
                    $scope.userForm.debt = false;
                    $scope.userForm.payFlag = true;
                }
            }


            $scope.pay = function () {
                if ($scope.userForm.payFlag) {

                    var payFlag = true;
                    //校验余额密码
                    if ($scope.banlanceForm.banlanceMoney > 0) {
                        if ($scope.banlanceForm.banlancePwd == null || $scope.banlanceForm.banlancePwd == '') {
                            $scope.banlanceForm.banlanceMsg = '【请输入支付密码】';
                            payFlag = false;
                        }
                    }
                    //校验礼品卡密码
                    if ($scope.cardForm.useCardMoney > 0) {
                        if ($scope.cardForm.cardPwd == null || $scope.cardForm.cardPwd == '') {
                            $scope.cardForm.cardMsg = '【请输入支付密码】';
                            payFlag = false;
                        }
                    }
                    if (payFlag) {
                        $scope.payOrder();
                    } else {
                        return;
                    }
                }
            }


            $scope.payOrder = function () {
                $scope.count();
                console.log("**********请求参数***********");
                console.log($scope.OrdersPayParam);
                console.log("**********请求结束***********");
                $scope.banlanceForm.balanceMsg = "";
                $scope.pointForm.pointMsg = "";
                $scope.cardForm.cardMsg = "";
                var payFlag = true;
                if ($scope.cardForm.giftCardNo == null || $scope.cardForm.giftCardNo == '') {
                    if (!$scope.cardForm.showCardPwd) {
                        $scope.cardForm.cardPwd = '';
                        $scope.cardForm.useCardMoney = 0;
                        $scope.cardForm.cardMsg = "";
                        payFlag = true;
                    } else {
                        $scope.cardForm.cardMsg = "卡号不能为空";
                        payFlag = false;
                    }
                } else {
                    if (!$scope.cardForm.showCardPwd) {
                        $scope.cardForm.giftCardNo = '';
                        $scope.cardForm.cardMsg = "";
                        $scope.cardForm.cardPwd = '';
                        $scope.cardForm.useCardMoney = 0;
                        payFlag = true;
                    } else {
                        if (($scope.cardForm.cardPwd == null || $scope.cardForm.cardPwd == '') &&
                            $scope.cardForm.useCardMoney > 0) {
                            $scope.cardForm.cardMsg = "";
                            payFlag = true;
                        } else if ($scope.cardForm.cardPwd == null || $scope.cardForm.cardPwd == '') {
                            $scope.cardForm.cardMsg = "支付密码不能为空";
                            payFlag = false;
                        } else if ($scope.cardForm.giftCardNo != $scope.payOldCardNo) {
                            $scope.cardForm.cardMsg = "卡号有变动，请重新读取";
                            payFlag = false;
                        }
                    }
                }
                var pointMoney = parseFloat($scope.pointForm.deductibleMoney);
                var payParam = {
                    'orderId': $scope.OrdersPayParam.orderId,
                    'customerId': $scope.order.sCustomerId,
                    'orderType': 1,
                    'marketChannelId': $scope.order.marketChannelId,
                    'payTypeParam': [],
                    'accountPayParam': {
                        'accountId': '',
                        'useMoney': $scope.banlanceForm.banlanceMoney,
                        'payPassword': $scope.banlanceForm.banlancePwd
                    },
                    'pointPayParam': {'usePoint': $scope.pointForm.usePoint, 'pointMoney': pointMoney},
                    'giftCardPayParam': {
                        'giftCardNo': $scope.cardForm.giftCardNo,
                        'useMoney': $scope.cardForm.useCardMoney,
                        'payPassword': $scope.cardForm.cardPwd
                    },
                    'detePay': $scope.userForm.debt,
                    'deteMoney': $scope.OrdersPayParam.debtMoney
                };

                /***
                 * 遍历数据操作
                 */
                for (var i in $scope.OrdersPayParam.orderPayTypeParams) {
                    if ($scope.OrdersPayParam.orderPayTypeParams[i].orderPayTypeId != 3
                        && $scope.OrdersPayParam.orderPayTypeParams[i].orderPayTypeId != 4
                        && $scope.OrdersPayParam.orderPayTypeParams[i].orderPayTypeId != 9) {
                        payParam.payTypeParam.push({
                            'orderPayTypeId': $scope.OrdersPayParam.orderPayTypeParams[i].orderPayTypeId,
                            'money': $scope.OrdersPayParam.orderPayTypeParams[i].money
                        });
                    }
                }

                if (payFlag) {
                    console.log("******请求参数******");
                    console.log(payParam);
                    console.log("******请求结束******");
                    OrderCommonRestService.payOrder(payParam).then(function (data) {
                        console.log("=============返回参数===========");
                        console.log(data);
                        console.log("=============返回参数===========");
                        if(data.code == 311){
                        	var msg = data.msg;
                        	var index = msg.indexOf('锁定');
                        	if(index >0){
                        		$scope.banlanceForm.showPayPwd = false;
                                $scope.banlanceForm.banlanceFlag = true;
                                $scope.pointForm.pointFlag = true;
                                $scope.userForm.debt = parseFloat($scope.userForm.debt) + parseFloat($scope.banlanceForm.banlanceMoney) + parseFloat(pointMoney);
                            	//$("#payMoneyPassword").val('');
                                $scope.pointForm.pointMsg = msg;//积分错误提示
                                $scope.banlanceForm.banlanceMoney = 0;
                                $scope.pointForm.usePoint = 0;
                                $scope.pointForm.deductibleMoney = 0;
                        	}
                        	$scope.banlanceForm.banlanceMsg = msg;
                        	return;
                        }else if (data.code == 200 ) {
                            $("#pay-box").modal("hide");
                            showModal($scope.order);
                        }else if(data.code == 340 || data.code == 341 || data.code == 343){
                        	MaiDialog.error(data.msg);
                        	$("#pay-box").modal("hide");
                        	$location.path("/view/sale/ppxsxz");
                        }
                        else{
                        	MaiDialog.alert(data.msg);
                        }
                    });

                }
//			OrderCommonRestService.payOrder($scope.OrdersPayParam).then(function(data){
//				if(data == "true"){
//					$("#pay-box").modal("hide");
//					showModal($scope.order);
//				}else{
//					MaiDialog.error(data,function(){
//						setTimeout(function(){document.body.className = "skin-blue fixed tooltip-f modal-open";},1000);
//					});
//				}
//			});	
            }

            $scope.$watch("userForm.debt", function (n_v, o_v) {
                $scope.count();
            })

            /***
             * 限制输入操作
             */
            $scope.moneyInput = function (obj, attr) {
                //先把非数字的都替换掉，除了数字和.
                obj[attr] = obj[attr].replace(/[^\d.]/g, "");
                //必须保证第一个为数字而不是.
                obj[attr] = obj[attr].replace(/^\./g, "");
                //必须保证第一个不是0
                obj[attr] = obj[attr].replace(/^0/g, "");
                //保证只有出现一个.而没有多个.
                obj[attr] = obj[attr].replace(/\.{2,}/g, "");

                obj[attr] = obj[attr].replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
                //保证.只出现一次，而不能出现两次以上
                obj[attr] = obj[attr].replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
            }

        });

        controllerModule.controller("PrintController", function ($scope, $timeout, $location, MaiDialog) {
            $scope.printVoucher = true;
            window.showModal = function (params) {
                $scope.order = params;
                $("#print-box").modal("show");
            }

            $scope.print = function () {
                if (checkPrint()) {
                    window.queryTicketFaceAndPrint({"orderId": $scope.order.sOrderId}, MaiDialog, function () {
                        if ($scope.printVoucher) {
                            $scope.$broadcast("watch-goodPayPrint", {orderId: $scope.order.orderId});
                        } else {
                           /* if ($scope.sourceType == "1") {
                            	//$rootScope.$broadcast("expand-menu-tree", "/view/order/advance_order_list", {"advanceOrderId": advanceOrderId});
                                $location.path("/view/sale/ppxsxz");
                            } else {
                                $location.path("/view/order/advance_order_list");
                            }*/
                        	 $scope.printClose();
                        }
                    });
                    $("#print-box").modal("hide");
                } else {
                    MaiDialog.alert("打印机未设置，请配置打印机");
                }
            }
            $scope.printClose = function () {
                $timeout(function () {
                    if ($scope.sourceType == "1") {
                        $location.path("/view/sale/ppxsxz");
                    } else {
                        $location.path("/view/order/advance_order_list");
                    }
                }, 10);
            }
        });
        controllerModule.controller("CustomerOrdersController", function ($scope, $rootScope, OrderCommonRestService, MaiDialog) {
            $scope.beforeSearchParams = {};

            window.projectShopCartControllerShow = function (customerId) {
                if (customerId == null) {
                    MaiDialog.error("请选择会员");
                    return;
                }
                $scope.$broadcast("reload-customerId", customerId);
                $scope.$broadcast('reloadGrid');
                $("#CustomerOrdersModal").modal("show");
            }
            //------------------------------------------------------START---------------------------------------------------------
            $scope.columnDefs = [];
            $scope.columnDefs.push({
                displayName: '下单时间',
                cellTemplate: function (entity) {
                    return "<span>" + entity.orderTime + "</span>"
                }
            });
            $scope.columnDefs.push({
                field: 'orderId',
                displayName: '订单号',
                cellTemplate: function (entity) {
                    return "<span>" + entity.orderId + "</span>"
                }
            });
            $scope.columnDefs.push({
                displayName: '实收金额',
                cellTemplate: function (entity) {
                    return "<span>" + decimalPoint(entity.money) + "</span>"
                }
            });
            $scope.columnDefs.push({
                displayName: '商品数量',
                cellTemplate: function (entity) {
                    return "<span>" + entity.goodCounts + "</span>"
                }
            });
            $scope.columnDefs.push({
                displayName: '项目名称',
                cellTemplate: function (entity) {
                    return "<span>" + entity.projectName + "</span>"
                }
            });
            //------------------------------------------------------END---------------------------------------------------------

        });


        //新建会员通用指令

        diretiveModule.directive('mplusCustomer', ['CartSaleCommonService', 'MaiDialog', function (CartSaleCommonService, MaiDialog) {
            return {
                scope: {
                    submitDo: '&'
                },
                restrict: "AE",
                controller: 'SaleAddCustomerController',
                templateUrl: rootPath + '/common/js/html/plusCustomer.html'
            };
        }]);


    });